from collections import OrderedDict
from pprint import pprint

from django import http
from django.core.paginator import Paginator, EmptyPage
from django.shortcuts import render
from django.views import View

from apps.goods.models import GoodsCategory, SKU, GoodsChannel
from apps.goods.utils import get_categories
from utils import constants


class ListView(View):
    """商品列表页"""

    def get(self, request, category_id, page_num):
        """提供商品列表页"""
        # 判断category_id是否正确
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return http.HttpResponseNotFound('GoodsCategory does not exist')

        # 接收sort参数：如果用户不传，就是默认排序规则
        sort = request.GET.get("sort", "default")

        # 按照排序规则查询该分类商品SKU信息
        if sort == "price":
            # 按照价格由高到低
            sort_field = "price"
        elif sort == "hot":
            # 按照销量由高到低
            sort_field = "-price"
        else:
            # "price" 和 "sales"以外的所有排序方式都归为default
            sort = "default"
            sort_field = "create_time"

        skus = SKU.objects.filter(spu__category3=category, is_launched=True).order_by(sort_field)

        # 创建分页器：每页N条数据
        paginator = Paginator(skus, constants.GOODS_LIST_LIMIT)
        # 获取每页商品数据
        try:
            page_skus = paginator.page(page_num)
        except EmptyPage:
            # 如果page_num不正确，默认给用户404
            return http.HttpResponseNotFound("empty page")
        # 获取列表页总页数
        total_page = paginator.num_pages

        # 渲染页面
        context = {
            "category": category,
            "sort": sort,  # 排序字段
            "page_skus": page_skus,  # 分页后数据
            "total_page": total_page,  # 总页数
            "page_num": page_num,  # 当前页数
        }
        return render(request, 'product.html', context)


class DetailView(View):
    def get(self, request):
        # 查询商品频道和分类
        categories_dict = OrderedDict()
        channels = GoodsChannel.objects.order_by("group_id", "sequence")
        for channel in channels:
            group_id = channel.group_id
            if group_id not in categories_dict:
                categories_dict[group_id] = {"channels": [], "sub_cats": []}
            category_1 = channel.category  # 当前频道 1级

            categories_dict[group_id]["channels"].append({
                "id": category_1.id,
                "name": category_1.name,
                "url": channel.url
            })

            for category_2 in category_1.subs.all():
                category_2_dict = {"id": category_2.id, "name": category_2.name, "sub_cats": []}
                for category_3 in category_2.subs.all():
                    category_3_dict = {"id": category_3.id, "name": category_3.name}
                    category_2_dict["sub_cats"].append(category_3_dict)
                categories_dict[group_id]["sub_cats"].append(category_2_dict)

        context = {
            "categories": categories_dict
        }

        return render(request, 'product.html', context)


class Xiangqing(View):
    """商品详情页"""

    def get(self, request, sku_id):
        """提供商品详情页"""
        # 获取当前sku的信息
        try:
            sku = SKU.objects.get(id=sku_id)
            print("111111", sku)
        except SKU.DoesNotExist:
            return render(request, "404.html")

        # 查询商品频道分类
        categories = get_categories()

        # 查询面包屑导航
        category = sku.spu.category3
        # breadcrumb = get_breadcrumb(category)

        # 取出所有的spu下的sku
        spu_specs_dict = {}
        all_skus = sku.spu.sku_set.all()
        print("1111111", all_skus)
        for sku_temp in all_skus:
            one_sku_specs = sku_temp.specs.all()
            for one_sku_spec in one_sku_specs:
                if (one_sku_spec.spec.name, one_sku_spec.option.value) not in spu_specs_dict:
                    spu_specs_dict[(one_sku_spec.spec.name, one_sku_spec.option.value)] = {sku_temp.id}
                else:
                    spu_specs_dict[(one_sku_spec.spec.name, one_sku_spec.option.value)].add(sku_temp.id)

        for op, val in spu_specs_dict.items():
            if sku.id in val:
                set_temp = val - {sku.id}  # 例如 {8, 6}
                spu_specs_dict[op] = {sku.id}  # 例如{4}
                for op_2, val_2 in spu_specs_dict.items():
                    for sku_id in set_temp:
                        if sku_id in val_2:
                            spu_specs_dict[op_2] = {sku_id}

        pprint(spu_specs_dict)

        spu_options = {}
        for op, val in spu_specs_dict.items():
            if op[0] not in spu_options:
                spu_options[op[0]] = [(op[1], val.pop())]
            else:
                spu_options[op[0]].append((op[1], val.pop()))

        pprint(spu_options)

        # 渲染页面
        context = {
            "categories": categories,
            # "breadcrumb": breadcrumb,
            "sku": sku,
            "specs": spu_options,
        }

        return render(request, "product_show.html", context)
